package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.QueryProductListRequest;
import com.aliyun.iot20180120.models.QueryProductListResponse;
import com.aliyun.iot20180120.models.QueryProductListResponseBody;
import com.zzyl.constant.CacheConstants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.service.DeviceService;
import com.zzyl.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.collections.RedisList;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    Client client;
    @Autowired
    AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    RedisTemplate<String,String>redisTemplate;
    @Override
    public void syncProjectList() {
        QueryProductListRequest rep = new QueryProductListRequest();
        rep.setCurrentPage(1);
        rep.setPageSize(100);
        rep.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryProductListRequest request = null;

        QueryProductListResponse response;
        try {
            response = client.queryProductList(rep);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_QUERY_PRODUCT_ERROR);
        }
        if (!response.getBody().getSuccess()) {
            throw new RuntimeException(response.getBody().getErrorMessage());
        }
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.getBody().getData().getList().getProductInfo();

        List<ProductVo> productVos = BeanUtil.copyToList(productInfo, ProductVo.class);
        //4.将产品列表存入redis
        redisTemplate.opsForValue().set((String) CacheConstants.ALL_PRODUCT_KEY, JSONUtil.toJsonStr(productVos));
    }
}
